package com.ftt.product.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ftt.Util;
import com.ftt.product.model.Order;
import com.ftt.product.model.ShoppingCar;
import com.ftt.product.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/SubmitOrder.do")
public class OrderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Object phone = req.getSession().getAttribute("phone");
//        Object real_name = req.getSession().getAttribute("real_name");
        if (phone == null) {
            Util.writerData(resp,new ArrayList<>());
        }else {
            ObjectMapper mapper = new ObjectMapper();
            Order order = mapper.readValue(req.getReader(), Order.class);
            String phoneStr = phone.toString();
//            String realNameStr = real_name.toString();
            String price = order.getTotal_price();
            List<ShoppingCar> list = order.getShoppingCars();
            ProductService servlet = new ProductService();
            boolean result = servlet.addOrder(phoneStr, price, list);
            System.out.println("添加订单结果"+result);
            Util.writerData(resp, list);
        }
    }
}
